﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;

namespace QuangNgai.cauhinh
{
    public partial class frmConnect : DevExpress.XtraEditors.XtraForm
    {
        private SqlConnection conn;
        private SqlCommand cmd;
        private SqlDataReader reader;
        public frmConnect()
        {
            InitializeComponent();
        }

        private void frmConnect_Load(object sender, EventArgs e) { this.FormBorderStyle = FormBorderStyle.None; }

        private void btnCancel_Click(object sender, EventArgs e) { this.Close(); }

        private void btnCheck_Click(object sender, EventArgs e)
        {
            cbbData.Items.Clear();
            if (txtServer.Text.Trim() != "")
            {
                lblStatus.Text = "Đang kiểm tra...";
                if (cbbAuth.SelectedIndex == 0)
                {
                    conn = new SqlConnection("Data Source=" + txtServer.Text +
                                                ";Initial Catalog=master;Integrated Security=True;");
                }
                else
                {
                    conn = new SqlConnection("Data Source=" + txtServer.Text +
                                                ";Initial Catalog=master;User Id=" + txtUsername.Text +
                                                ";Password=" + txtPassword.Text + ";");
                }
                cmd = new SqlCommand("SP_DATABASES", conn);
                try
                {
                    conn.Open();
                    reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        cbbData.Items.Add(reader[0].ToString());
                    }
                    lblStatus.Text = "Kết nối thành công!";
                }
                catch (SqlException)
                {
                    lblStatus.Text = "Kết nối thất bại!";
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                        conn.Close();
                    conn.Dispose();
                    cmd.Dispose();
                }
            }
            else
            {
                lblStatus.Text = "LỖI: CHƯA CHỌN SERVER!";
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            string connStr = null;//"Data Source=localhost;Initial Catalog=QLDiemCap2;" +
            //"Persist Security Info=True;User ID=sa;Password=12345";
            // Get the application configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None);

            // Save the configuration file.
            if (cbbAuth.SelectedIndex == 1)
            {
                connStr = "Data Source=" + txtServer.Text.Trim() + ";" +
                            "Initial Catalog=" + cbbData.Text.Trim() +
                            ";Persist Security Info=True; " +
                            "User ID = " + txtUsername.Text.Trim() + "; " +
                            "password = " + txtPassword.Text.Trim() + ";";
            }
            else
            {
                connStr = "Data Source=" + txtServer.Text.Trim() + ";" +
                            "Initial Catalog=" + cbbData.Text.Trim() +
                            ";Integrated Security=True";
            }
            config.ConnectionStrings.ConnectionStrings["QuangNgai.Properties.Settings.lutru_UBND98Con"].ConnectionString = connStr;
            config.Save(ConfigurationSaveMode.Modified);
            MessageBox.Show("Khởi động lại chương trình để các thay đổi có hiệu lực", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Close();
        }

        private void btnCai_Click(object sender, EventArgs e)
        {
            bool dbExisted = false;

            var DBPath = Path.GetDirectoryName(Application.ExecutablePath) + @"\cosodulieu";

            var detachSQL = "master.dbo.sp_detach_db @dbname = N'lutru_UBND98'";
            var createSQL =
                            "CREATE DATABASE [lutru_UBND98] ON " +
                            "( FILENAME = N'" + DBPath + "\\lutru_UBND98_Data.MDF' ), " +
                            "( FILENAME = N'" + DBPath + "\\lutru_UBND98_Log.LDF' ) " +
                            "FOR ATTACH ";

            cmd = new SqlCommand("SP_DATABASES", conn);
            try
            {
                // kiem tra da ton tai hay chua
                conn.Open();
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    if (reader[0].ToString().Equals("lutru_UBND98"))
                    {
                        dbExisted = true;
                        break;
                    }
                }
                lblStatus.Text = "Thực hiện cài mới cơ sở dữ liệu";

                // xoa db cu
                if (!dbExisted)
                {
                    try { cmd.CommandText = detachSQL; cmd.ExecuteNonQuery(); }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Lỗi xảy ra trong quá trình giỡ cơ sở dữ liệu cũ: \n" + ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                // cai
                cmd.CommandText = createSQL; cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                if (ex.Message.Contains("Login failed for user"))
                {
                    lblStatus.Text = "Sai tài khoản hoặc mật khẩu";
                }
                lblStatus.Text = "Kết nối thất bại!";
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                    conn.Close();
                conn.Dispose();
                cmd.Dispose();
            }

        }

    }// class
}